//Copyright 2009 Dominik Punz
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

#ifndef jniString_h__
#define jniString_h__

#include "jniReference.h"

class CJniString : public CJniLocalReference<jstring>
{
public:
  CJniString(BSTR bstring) : CJniLocalReference<jstring>(0)
  {
    ws = bstring;
    Attach(jni.Env()->NewString((jchar*)ws.c_str(),ws.length()));
  }

  CJniString(const std::wstring& str) : CJniLocalReference<jstring>(0)
  {
    ws = str;
    Attach(jni.Env()->NewString((jchar*)str.c_str(), str.length()));
  }
  
  CJniString(jstring jstr) : CJniLocalReference<jstring>(jstr)
  {
    InitWString();
  }

  CJniString(jobject jobj) : CJniLocalReference<jstring>((jstring)jobj)
  {
    InitWString();
  }

  jstring JString() { return Get(); }
  const std::wstring& WString() { return ws; }

  // TODO
  // Assign must be overrided

private:
  void InitWString()
  {
    if (Get())
    {
      const wchar_t* chars = (wchar_t*)jni.Env()->GetStringChars(Get(), NULL); 
      if (jni.Env()->ExceptionCheck())
      {
        jni.Env()->ExceptionClear();
        Release();
      }
      else if (chars)
      {
        ws = chars;
        jni.Env()->ReleaseStringChars(Get(), (jchar*)chars);
      }
    }
    else
    {
      ws = L"null";
    }
  }
private:
  CJniEnvironment jni;
  std::wstring ws;

};

#endif // jniString_h__